package cn.ichiva.common.io;

import java.io.*;

public class IOHelper {

    public static void writeObject(String fileName,Object obj) throws IOException {
        File file = new File(fileName);
        writeObject(file,obj);
    }

    public static void writeObject(File file,Object obj) throws IOException {
        File parentFile = file.getParentFile();
        if(null != parentFile && !parentFile.exists()) parentFile.mkdirs();
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file))){
            out.writeObject(obj);
        }
    }


    public static Object readObject(String name) throws IOException, ClassNotFoundException {
        return readObject(new File(name));
    }

    public static Object readObject(File name) throws IOException, ClassNotFoundException {
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(name))){
            return in.readObject();
        }
    }

    public static void write(File file, byte[] val) throws IOException {
        File parent = file.getParentFile();
        if(parent!=null) parent.mkdirs();

        try (OutputStream out = new FileOutputStream(file)){
            out.write(val);
        }
    }

    public static byte[] read(File file) throws IOException {
        try (InputStream in = new FileInputStream(file)){
            byte[] res = new byte[in.available()];
            in.read(res);
            return res;
        }
    }

    public static void cope(InputStream in, OutputStream out) throws IOException {
        byte[] tem = new byte[1024];
        int read = in.read(tem);
        while (read != -1){
            out.write(tem,0,read);
            read = in.read(tem);
        }
        out.flush();
    }

    public static String readAll(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        cope(in,out);
        return new String(out.toByteArray(),"utf-8");
    }
}
